﻿String.prototype.trimEnd = function (s) {
    s = (s ? s : "\\s");
    s = ("(" + s + ")");
    var reg_rTrim = new RegExp(s + "*$", "g");
    return this.replace(reg_rTrim, "");
}
$(function () {
    $("#upload_d .tablist").tabs("#upload_d .js_tabcnt > div");
    //初始化变量
    var d_outer = $("#upload_d").parents(".d-outer");
    var settings = { okfun: "", type: "image", uploadparams: "" };
    var param = d_outer.data("param");
    param = $.extend(true, settings, param);
    var dialog = d_outer.data("uploadDialog");
    var uploadButton = '<div class="btn_big"><span class="ico ico_uploader_image"></span>选择图片</div>', dragZone = '<div class="btn_big"><span class="ico ico_uploader_image"></span>拖动到此处</div>', uploadButton2 = "<span class='ico ico_upload_image'></span>", sizeLimit = 209715200, allowedExtensions = ['jpeg', 'jpg', 'gif', 'png'], oktipmessage = "请至少选择一张图片", droptipmessage = " 按住 CTRL 可选择多个图片，<br />或直接将图片拖入方框内上传。", dialogtitle = "上传图片", tab_title_1 = "上传图片", tab_title_2 = "在线管理", tab_title_3 = "网络图片";

    if (param.multi) {
        dialogtitle = "上传图片（多图片）"
        droptipmessage = "按住 CTRL 可选择多个图片，<br />或直接将图片拖入方框内上传。";

    }
    else {
        dialogtitle = "上传图片（单图片）"
        droptipmessage = "你可以直接将图片拖入方框内上传。";
    }
    if (param.type.toLowerCase() === "file") {
        uploadButton = '<div class="btn_big"><span class="ico ico_uploader_file"></span>选择文件</div>';
        dragZone = '<div class="btn_big"><span class="ico ico_uploader_file"></span>拖动到此处</div>';
        uploadButton2 = "<span class='ico ico_upload_file'></span>";
        sizeLimit = 209715200;
        allowedExtensions = [];
        oktipmessage = "请至少选择一个文件";

        if (param.multi) {
            dialogtitle = "上传文件（多文件）"
            droptipmessage = " 按住 CTRL 可选择多个文件，<br />或直接将文件拖入方框内上传。";
        }
        else {
            dialogtitle = "上传文件（单文件）"
            droptipmessage = " 您可以直接将文件拖入方框内上传。";
        }
        tab_title_1 = "上传文件";
        tab_title_3 = "网络文件";
    }
    $("#upload_d .tablist a").eq(0).text(tab_title_1);
    $("#upload_d .tablist a").eq(2).text(tab_title_3);
    if (param.type.toLowerCase() === "file") {
        $("#upload_d .tablist a:gt(1)").remove();
        $("#upload_d .netpic").remove();
    }


    $(".js_uploader").parent().find(".message").html(droptipmessage);
    $("#upload_d").find(".upload_d_t").html(dialogtitle);


    //初始化 fineuploader
    var z_index = 99;
    var manualuploader = new qq.FineUploader({
        element: $('.js_uploader')[0],
        request: {
            endpoint: '/m/file/fineuploader',
            params: param.uploadparams
        },
        maxConnections: 1,
        autoUpload: true,//是否自动上传
        text: {//按钮文字支持html
            uploadButton: uploadButton,
            dragZone: dragZone
        },
        retry: {
            enableAuto: true,
            showButton: true
        },
        multiple: param.multi,//是否允许多条上传
        validation: {//上传验证
            allowedExtensions: allowedExtensions,
            sizeLimit: sizeLimit
        },
        callbacks: {
            onUpload: function (id, name) {
                var $uploader = $(".js_uploader").find(".qq-uploader");
                var $ul = $uploader.find(".qq-upload-list"), $li = $uploader.find(".qq-upload-list li[data-id='" + id + "']"), $processbar = $li.find(".qq-progress-bar"), $button = $uploader.find(".qq-upload-button"), $drop = $uploader.find(".qq-upload-drop-area"); $li.css("z-index", z_index++);
                $uploader.parents(".uploaderbox").css({ "padding-top": "20px", "padding-bottom": "0" }).find(".message").remove();
                $li.attr("data-id", id);
                var html = '<div class="ico qq-file-type ' + getFileTypeIco(name) + '"></div>';
                $li.append(html);
                $li.find(".qq-upload-file").css("cursor", "pointer");
                $li.attr("data-id", id);
                $drop.remove();
                $button.addClass("qq-upload-button-1");
                $button.children("div").html(uploadButton2);
                $ul.find(".qq-upload-li-add").append($button);
            },
            onComplete: function (id, fileName, result) {
                if (result.success) {
                    var $uploader = $(".js_uploader").find(".qq-uploader");
                    var $ul = $uploader.find(".qq-upload-list"), $li = $uploader.find(".qq-upload-list li[data-id='" + id + "']"), $processbar = $li.find(".qq-progress-bar"), $button = $uploader.find(".qq-upload-button"), $drop = $uploader.find(".qq-upload-drop-area");
                    $li.attr("data-meta", "{filePath:'" + result.file + "',title:'" + fileName + "',description:''}");
                    $li.find(".qq-upload-file").css("cursor", "pointer");
                    $li.append('<label class="checkbox_own qq-upload-li-select"><input type="checkbox" checked="checked"></label>');
                    $li.find(".qq-upload-file").addClass("qq-upload-file-1");
                    $li.find(".qq-upload-retry").hide();
                    $li.find(".qq-progress-bar-wrap").hide();
                    if (param.type === "image") {
                        $li.find(".qq-upload-file").empty();
                        $li.find(".qq-file-type").remove();
                        $li.children().first().before("<div class='img_wrap'><img src='" + result.file + "' /></div>")
                    }

                    var html = "<div class='fileinfo js_fileinfo'><div class='box clearfix'><span class='ico arraw ico_arraw_up_white'></span><input type='text' class='text w_24-5 js_watermark' data-msg='在这里填写标题信息' value='" + fileName + "' />"
                        + "<textarea class='textarea js_watermark' data-msg='在这里填写描述信息'></textarea>"
                        + "<div class='btnbox'><span class='btn btn_file_edit js_info_ok'></span><span class='btn btn_file_del js_info_reset'></span></div></div></div>";
                    $li.append(html)

                    html = '<div class="fun"><span class="btn js_adddes">添加描述</span></div>'
                    $li.append(html);


                    $li.click(function (e) {
                        var $this = $(this);
                        if (param.multi) {
                            $(this).find(".checkbox_own").trigger("click.own");
                            $(this).hasClass("qq-list-uploaded-current") ? $(this).removeClass("qq-list-uploaded-current") : $(this).addClass("qq-list-uploaded-current");
                        }
                        else {
                            $(this).find(".checkbox_own").trigger("click.own");
                            $(this).hasClass("qq-list-uploaded-current") ? $(this).removeClass("qq-list-uploaded-current") : $(this).addClass("qq-list-uploaded-current");
                            $(this).siblings("qq-list-uploaded-current").each(function () {
                                $(this).removeClass("current");
                                $(this).find(".checkbox_own").trigger("click.own");
                            })
                        }

                    });


                    bindGlobalEvents($li);


                    $.each($('.js_watermark'), function (i, n) {
                        if (typeof ($(n).attr('data-msg')) != 'undefined')
                            $(n).watermark($(n).attr('data-msg'));
                    });
                    $li.trigger("click");

                } else {
                    alert("上传失败!");
                }
            },
            onAllComplete: function (succeeded, failed) {
                alert("上传陈功！");
                if (succeeded.length > 0) {
                    var $uploader = $(".js_uploader").find(".qq-uploader");
                    var $ul = $uploader.find(".qq-upload-list");
                    $ul.find(".checkbox_own").first().trigger("click.own");
                }
            }
        }
    });

    function getFileTypeIco(fileName) {
        var file_type = fileName.substring(fileName.lastIndexOf(".") + 1);
        file_type = file_type.toLowerCase();
        var file_type_ico = "";
        if (file_type === "doc" || file_type === "docx")
            file_type_ico = "ico_filetype_word";
        else if (file_type === "xls" || file_type === "xlsx")
            file_type_ico = "ico_filetype_excel";
        else if (file_type === "ppt" || file_type === "pptx")
            file_type_ico = "ico_filetype_ppt";
        else if (file_type === "pdf")
            file_type_ico = "ico_filetype_pdf";
        else if (file_type === "jpg" || file_type === "jpeg" || file_type === "png" || file_type === "gif" || file_type === "tif" || file_type === "tiff" || file_type === "bmp" || file_type === "tga")
            file_type_ico = "ico_filetype_image";
        else if (file_type === "rar" || file_type === "zip" || file_type === "tar" || file_type === "7-zip" || file_type === "gzip" || file_type === "iso" || file_type === "jar" || file_type === "cab")
            file_type_ico = "ico_filetype_rar";

        return file_type_ico;
    }

    //事件绑定


    $("#upload_d .opbtnbox .okbtn").click(function (e) {
        e.preventDefault();
        var $uploader = $("#upload_d .js_uploader").find(".qq-uploader");
        var $ul = $uploader.find(".qq-upload-list"), $li = $ul.find("li");
        $ul.find("li .js_fileinfo:visible").find(".js_info_ok").trigger("click");
        var filepaths = [];
        if ($(".uploaderbox").is(":visible")) {
            var $uploader = $(".js_uploader").find(".qq-uploader");
            var $ul = $uploader.find(".qq-upload-list"), $lis = $uploader.find(".qq-upload-list li.qq-list-uploaded-current");
            if ($lis.length == 0) {
                alert(oktipmessage, "error");
                return false;
            }
            $lis.each(function () {
                filepaths.push($(this).metadata());
            })
        }
        else if ($(".onlinepic").is(":visible")) {
            var $ul = $(".onlinepic").find("ul"), $lis = $ul.find("li.current");
            if ($lis.length == 0) {
                alert(oktipmessage, "error");
                return false;
            }
            $lis.each(function () {
                filepaths.push($(this).metadata());
            })
        }
        else if ($(".netpic").is(":visible")) {
            var $ul = $(".netpic").find("ul"), $lis = $ul.find("li.current");
            if ($lis.length == 0) {
                alert(oktipmessage, "error");
                return false;
            }
            $lis.each(function () {
                filepaths.push($(this).metadata());
            })
        }
        if (param.okfun != null && param.okfun != "") {

            if (typeof (param.okfun) === "function") {
                param.okfun(filepaths);
            }
            else if (typeof (eval(param.okfun)) === "function") {
                eval(param.okfun + "(filepaths)");
            }

        }
        else
            d_outer.data("files", filepaths);
        dialog.close();
    });

    $("#upload_d .opbtnbox .cancelbtn").click(function (e) {
        dialog.close();
    })


    //tab切换
    $("#upload_d .tablist").tabs("#upload_d .js_tabcnt > div");




    //加载网络图片
    $('#fileonline').click(function () {
        $.post($(this).attr('data-href'), { type: param.type }, function (data) {
            //var html = '';
            //var images = data;
            //if (param.type == "image") {
            //    var z_index = 9999999;
            //    for (var i = 0; i < images.length; i++) {
            //        html += '<li data-meta=\'{filePath:"' + images[i].Path + '",title:"' + images[i].Title + '",description:"' + images[i].Description + '"}\' style="position:relative; z-index:' + (z_index--) + '"><img src="' + images[i].Path + '" /><div class="fun"><span class="btn js_adddes">添加描述</span></div>'
            //            + "<div class='fileinfo js_fileinfo'><div class='box clearfix'><span class='ico arraw ico_arraw_up_white'></span><input type='text' class='text w_24-5 js_watermark' data-msg='在这里填写标题信息' value=" + images[i].Title + " />"
            //            + "<textarea class='textarea js_watermark' data-msg='在这里填写描述信息'>" + images[i].Description + "</textarea>"
            //            + "<div class='btnbox'><span class='btn btn_file_edit js_info_ok'></span><span class='btn btn_file_del js_info_reset'></span></div></div></div>"
            //            + '<label class="checkbox_own qq-upload-li-select"><input type="checkbox" checked="checked"></label>'
            //            + '</li>';
            //    }
            //}
            //else if (param.type == "file") {
            //    for (var i = 0; i < images.length; i++) {
            //        html += '<li data-meta=\'{filePath:"' + images[i].FileName + '",title:"",description:""}\' style="position:relative; z-index:' + (z_index--) + '"><div class="fun"><span class="btn js_adddes">添加描述</span></div>'
            //             + "<div class='fileinfo js_fileinfo'><div class='box clearfix'><span class='ico arraw ico_arraw_up_white'></span><input type='text' class='text w_24-5 js_watermark' data-msg='在这里填写标题信息' />"
            //             + "<textarea class='textarea js_watermark' data-msg='在这里填写描述信息'></textarea>"
            //             + "<div class='btnbox'><span class='btn btn_file_edit js_info_ok'></span><span class='btn btn_file_del js_info_reset'></span></div></div></div>"
            //             + '<div class="file_type"><span class="ico ' + getFileTypeIco(images[i]) + '"></span></div>'
            //             + '<div class="file_title"></div>'
            //             + '<label class="checkbox_own qq-upload-li-select"><input type="checkbox" checked="checked"></label>'
            //             + '</li>';
            //    }
            //}
            //html = '<ul class="list_img">' + html + '</ul>';
            $('#upload_d .onlinepic').html(data);
            bindEvents();
            bindGlobalEvents($("#upload_d .onlinepic .list_img li"));
            bindAsyncEvent();
        });
    });

    function bindAsyncEvent() {
        $("#upload_d .onlinepic .pager a").click(function (e) {
            e.preventDefault();
            var $this = $(this);
            var href = $this.attr("href");
            if (href != "" && href != "#" && href != "javascript:") {
                $('#fileonline').attr("data-href", href).trigger("click");
            }
        });
        $("#upload_d .onlinepic .funsearch form").submit(function (e) {
            e.preventDefault();
            var $this = $(this);
            $('#fileonline').attr("data-href", "/m/file/ProcessRequest?query.Title=" + $this.find('input[name="Title"]').val()).trigger("click");
            return false;
        });
    }

    function bindEvents() {
        $("#upload_d .onlinepic .list_img li,#upload_d .netpic .preview ul li").click(function (e) {
            $(this).find(".checkbox_own").trigger("click.own");
            $(this).hasClass("current") ? $(this).removeClass("current") : $(this).addClass("current");
            if (!param.multi) {
                $(this).siblings(".current").each(function () {
                    $(this).removeClass("current");
                    $(this).find(".checkbox_own").trigger("click.own");
                });
            }
        });

    }

    function bindGlobalEvents($li) {
        $li.find(".checkbox_own").click(function (e) {
            $(this).trigger("click.own");
        });

        $li.find(".js_adddes").click(function (e) {
            e.stopPropagation();
            $(this).parents("li").siblings("li").find(".js_fileinfo:visible").find(".js_info_ok").trigger("click");
            $(this).parent().siblings(".js_fileinfo").show();
            $(this).parent().hide();
        })

        $li.find(".js_fileinfo").click(function (e) {
            e.stopPropagation();
        })

        $li.find(".js_fileinfo .js_info_ok").click(function (e) {
            e.preventDefault();
            var $this = $(this), $titleInput = $this.parents(".js_fileinfo").find("input"), $desInput = $this.parents(".js_fileinfo").find("textarea"), $li = $this.parents("li");
            var params = $li.metadata();
            params.title = $titleInput.val();
            params.description = $desInput.val();
            $this.parents("li").attr("data-meta", JSON.stringify(params));
            $this.parents(".js_fileinfo").hide().siblings(".fun").show();
        })

        $li.find(".js_fileinfo .js_info_reset").click(function (e) {
            e.preventDefault();
            var $this = $(this), $titleInput = $this.parents(".js_fileinfo").find("input"), $desInput = $this.parents(".js_fileinfo").find("textarea"), $li = $this.parents("li");
            $titleInput.val("");
            $desInput.val("");
            $this.parents(".js_fileinfo").hide().siblings(".fun").show();
        })
    }





    //添加网络图片、文件
    var z_index = 9999999;
    $("#upload_d .netpic .neturl .btn").click(function () {
        var $this = $(this), $input = $this.prev(), value = $input.val(), $ul = $this.parent().siblings(".preview").find("ul");
        if (value == "") {
            alert("请填写一个网络路径！", "error");
            return false;
        }
        else {
            var reg = /^http(s?):\/\//
            if (!reg.test(value)) {
                alert('网络路径必须已“http://”或“https://”开头');
                return false;
            }
            else {
                var html = '<li data-meta=\'{filePath:"' + value + '",title:"",description:""}\' style="position:relative; z-index:' + (z_index--) + '"><img src="' + value + '" /><div class="fun"><span class="btn js_adddes">添加描述</span></div>'
                        + "<div class='fileinfo js_fileinfo'><div class='box clearfix'><span class='ico arraw ico_arraw_up_white'></span><input type='text' class='text w_24-5 js_watermark' data-msg='在这里填写标题信息'  />"
                        + "<textarea class='textarea js_watermark' data-msg='在这里填写描述信息'></textarea>"
                        + "<div class='btnbox'><span class='btn btn_file_edit js_info_ok'></span><span class='btn btn_file_del js_info_reset'></span></div></div></div>"
                        + '<label class="checkbox_own qq-upload-li-select"><input type="checkbox" checked="checked"></label>'
                        + '</li>';
                $ul.append(html);
                $ul.find("li").css("cursor", "pointer").trigger("click");
            }
        }
        bindEvents();
        bindGlobalEvents($("#upload_d .netpic .preview ul li"));
    });
});